"""
 封装 3级 分类数据的获取
"""
from collections import OrderedDict

from apps.goods.models import GoodsChannel


def get_categories():

    categories = OrderedDict()

    # 1.查询 商品频道表 GoodsChannel--所有频道数据 ---37个
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    # 2.遍历37个频道
    for channel in channels:
        # 3.每个频道--外键属性  group_id --频道组--11组
        group_id = channel.group_id

        # 4.判断当前字典  到底有没有 这个key --group_id
        if group_id not in categories:
            # 5. 生成 每组的 字典格式数据  categories[group_id] = {'channels':[], 'sub_cats':[]}
            categories[group_id] = {'channels': [], 'sub_cats': []}

        # 6.频道chanel根据category_id -- 取出一级分类 id name url
        cat1 = channel.category
        cat1.url = channel.url
        categories[group_id]['channels'].append(cat1)

        # 7.一级分类---二级 ---三级
        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            # 二级 ---三级
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)

    return categories
